package com.baor.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    public static String md5(String str){
        //md5加密java
        if (str == null) {
            return null;
        }
        try {
            // 获取MD5消息摘要实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算消息摘要（使用UTF-8编码）
            byte[] bytes = md.digest(str.getBytes());
            // 转换为十六进制字符串
            return bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            // MD5算法是Java标准算法，理论上不会抛出此异常
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        char[] chars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            // 取字节的高4位和低4位转换为十六进制字符
            int b = bytes[i] & 0xFF;
            chars[i * 2] = HEX_CHARS[b >>> 4];
            chars[i * 2 + 1] = HEX_CHARS[b & 0x0F];
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        String admin = md5("admin");
        System.out.println(admin);
    }
}
